/*!
 * 工具类模块
 * @author Sherlock
 * 无业务的工具型模块
 * 各个方法使用请参照注释
 */
require( './style.less' );

define( [ 'jquery', 'constants', 'transit' ], function( $, c ) {
  var img02Store = c.img02Store;
  var returnParam = {
    getUrlParam: function( url, name ) {
      if ( typeof name === 'undefined' ) {
        name = url;
        url = window.top.location.href;
      }
      try {
        url = decodeURI( url );
      } catch ( e ) {}
      var reg = new RegExp( '' + name + '=([^&]*)' );
      var r = url.match( reg );
      // 去除参数井号后的内容
      if ( r != null ) {
        var pramValue = unescape( r[ 1 ] );
        if ( pramValue.indexOf( '#' ) > -1 ) {
          return pramValue.substr( 0, pramValue.indexOf( '#' ) );
        } else {
          return pramValue;
        }
      }
      return null;
    },
    /*转义特殊字符*/
    escapeHtml: function( string ) {
      var entityMap = {
        "&": "&amp;",
        "<": "&lt;",
        ">": "&gt;",
        '"': '&quot;',
        "'": '&#39;',
        "/": '&#x2F;'
      };
      return String( string ).replace( /[&<>"'\/]/g, function( s ) {
        return entityMap[ s ];
      } );
    },
    encodeHtml: function( str ) {
      if ( !str ) return '';
      s = str.replace( /&/g, "&gt;" );
      s = s.replace( /</g, "&lt;" );
      s = s.replace( />/g, "&gt;" );
      s = s.replace( / /g, "&nbsp;" );
      s = s.replace( /\'/g, "&#39;" );
      s = s.replace( /\"/g, "&quot;" );
      s = s.replace( /\n/g, "" );
      return s;
    },
    /**
     * 字符串包含
     */
    contains: function( str, substr ) {
      return new RegExp( substr ).test( str );
    },
    /*
     * 替换当前url 并不导致浏览器页面刷新
     * name 参数名
     * value 参数值
     */
    replaceUrl: function( name, value ) {
      var obj = new Object();
      obj[ name ] = value;
      obj.rand = Math.random();
      history.replaceState( obj, '', '?' + name + '=' + value );
    },
    /**
     * 判断是否为微信图片 如果是就返回一个带转发的地址
     */
    wechartImgCheck: function( url, isDomain ) {
      var _regexWeChart = /^((http|https):\/\/mmbiz(\.qpic|\.qlogo)\.cn)(.+)/;
      var tempUrl = '';
      var filterArrry = [
        'hiphotos.baidu.com',
        'img.hb.aicdn.com',
        'cmscdn.xitek.com',
      ];

      function hostsCheck( url ) {
        var isInHosts = false;
        $.each( filterArrry, function( k, v ) {
          if ( url.indexOf( v ) > -1 ) {
            isInHosts = true;
            return false;
          }
        } );
        return isInHosts;
      }

      try {
        var urlObj = new URL( url );
      } catch ( e ) {
        return url;
      }

      if ( _regexWeChart.test( url ) || hostsCheck( urlObj.hostname ) ) {
        if ( isDomain ) {
          tempUrl = '//' + document.location.hostname + img02Store + url;
        } else {
          tempUrl = img02Store + url;
        }
        return tempUrl;
      } else {
        return url || '';
      }
    },
    strlen: function( str ) {

      var len = 0;
      for ( var i = 0; i < str.length; i++ ) {
        var c = str.charCodeAt( i );
        //单字节加1
        if ( ( c >= 0x0001 && c <= 0x007e ) || ( 0xff60 <= c && c <= 0xff9f ) ) {
          len++;
        } else {
          len += 2;
        }
      }
      return len;
    },
    /**
     * 检查是否是url地址
     * @param url 需要验证的地址 
     */
    isUrlCheck: function( url ) {
      return /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/.test( url );
    },
    // 获取字符的长度
    getStrChartLen: function( str ) {
      return str ? str.replace( /[^\x00-\xff]/g, 'xx' ).length : 0;
    },
    // 获取全角半角混合的长度 （两个半角算一 不足两个不计入）
    getStrCountLen: function( str ) {
      var halfAngleLen = str.match( /[\x00-\xff]/g ).join( '' ).length;
      var fullAngleLen = str.match( /[^\x00-\xff]/g ).join( '' ).length;
      return parseInt( halfAngleLen / 2 + fullAngleLen );
    },
    // 请求图片的对象
    prepImageRequest: function( url, callbackParam, fn ) {
      var img = new Image();
      var errorImg = new Image();
      var isReturn = false;
      errorImg.src = c.resPath + '/images/wuyulantu.png';

      function loopGetWH() {
        if ( img.width ) {
          hasFunction( img );
        }
      }

      function hasFunction( img ) {
        clearInterval( interval );
        if ( !isReturn ) {
          isReturn = true;
          if ( fn ) {
            fn( img, callbackParam );
          } else {
            if ( callbackParam ) {
              callbackParam( img );
            }
          }
        }
      }
      img.src = url;
      var interval = setInterval( loopGetWH, 40 );
      img.complete = function() {

      }
      img.onerror = function() {
        // 取消定时获取宽高
        hasFunction( errorImg );
      }
      img.onload = function() {
        // 取消定时获取宽高
        hasFunction( img );
      }
    },
    scrollMaxWin: function( fn, percent ) {
      //$callback  =  typeof fn  ===  "function"  ?  fn  :  undefined;
      percent = percent || 10;
      var $thisObj = $( window );
      $thisObj.scroll( function() {
        var scrollHeight = $( 'body' )[ 0 ].scrollHeight;
        var thisHeight = $thisObj.outerHeight();
        var scrollTop = $thisObj.scrollTop();

        if ( scrollHeight - ( scrollTop + thisHeight ) <= percent ) {
          if ( fn ) {
            fn.call( $thisObj[ 0 ], thisHeight )
          }
        }
      } );
    },
    /**
     * MD5编码
     * @param 
     */
    md5: require( 'md5' ),
    /**
     * 自动填充字符串数据 {name}
     * @param elementStr 要填充的字符串
     * @param dataObj 要填充的数据  支持点语法 支持简单的表达式
     */
    fullData: function( elementStr, d ) {
      return elementStr ? ( function() {
        var fieldArray = elementStr.match( /\{(.*?)\}/g ).join( '^' ).replace( /\{|\}/g, '' ).split( '^' );
        for ( var i in fieldArray ) {
          var fieldStr = fieldArray[ i ];
          if ( fieldStr !== '' ) {
            var fieldVal = eval( '(' + fieldStr + ')' );
            elementStr = elementStr.replace( new RegExp( '{' + this.regExpReplace( fieldStr ) + '}', 'g' ), fieldVal == null ? '' : fieldVal );
          }
        }
        return elementStr;
      }.call( this ) ) : '';
    },
    /**
     * 直接填充数据到页面
     * @param elementStr 要填充的字符串
     * @param dataObj 要填充的数据数组
     * @param appendTo 容器对象
     */
    fullDataTo: function( elementStr, dataArray, appendTo ) {
      if ( !appendTo ) return;
      var html = '';
      for ( var i in dataArray ) {
        html += this.fullData( elementStr, dataArray[ i ] );
      }
      return $( appendTo ).append( html );
    },
    /**
     * 替换字符串中的正则敏感字符
     */
    regExpReplace: function( str ) {

      str = str || '';

      return str.replace( /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&' );
    },
    /**
     * 七牛图片以及外部图片缩略图处理
     */
    imgTimthumb: function( str, w, h ) {
      var urlObj = null;
      try {
        urlObj = new URL( str );
      } catch ( e ) {
        return str;
      }
      if ( !w && !h )
        w = h = 100;
      if ( !h )
        h = w;
      return urlObj[ 'hostname' ].indexOf( 'bigwe.com' ) > -1 ? ( urlObj[ 'href' ] + '?imageView2/2/w/' + w + '/h/' + h + '' ) : ( c.surpportHostName + '/timthumb.php?w=' + w + '&h=' + h + '&src=' + urlObj[ 'href' ] );
    },
    /**
     * url解析
     */
    parseURL: function( url ) {
      var a = document.createElement( 'a' );
      a.href = url;
      return {
        source: url,
        href: url,
        origin: a.origin,
        protocol: a.protocol,
        host: a.hostname,
        hostname: a.hostname,
        port: a.port,
        query: a.search,
        params: ( function() {
          var ret = {},
            seg = a.search.replace( /^\?/, '' ).split( '&' ),
            len = seg.length,
            i = 0,
            s;
          for ( ; i < len; i++ ) {
            if ( !seg[ i ] ) {
              continue;
            }
            s = seg[ i ].split( '=' );
            ret[ s[ 0 ] ] = s[ 1 ];
          }
          return ret;
        } )(),
        file: ( a.pathname.match( /\/([^\/?#]+)$/i ) || [ , '' ] )[ 1 ],
        hash: a.hash.replace( '#', '' ),
        path: a.pathname.replace( /^([^\/])/, '/$1' ),
        relative: ( a.href.match( /tps?:\/\/[^\/]+(.+)/ ) || [ , '' ] )[ 1 ],
        segments: a.pathname.replace( /^\//, '' ).split( '/' )
      };
    },
    // 判断图片加载的函数 -- callback 回调函数
    isImgLoad: function( callback ) {
      var t_img; // 定时器
      var isLoad = true; // 控制变量
      // 查找所有封面图，迭代处理
      $( '.picture_list img' ).each( function() {
        // 找到为0就将isLoad设为false，并退出each
        if ( this.height === 0 ) {
          isLoad = false;
          return false;
        }
      } );
      // 为true，没有发现为0的。加载完毕
      if ( isLoad ) {
        clearTimeout( t_img ); // 清除定时器
        // 回调函数
        callback();
        // 为false，因为找到了没有加载完成的图，将调用定时器递归
      } else {
        isLoad = true;
        t_img = setTimeout( function() {
          isImgLoad( callback ); // 递归扫描
        }, 500 ); // 我这里设置的是500毫秒就扫描一次，可以自己调整
      }
    }
  }
  $.extend( $.easing, {
    easeinout: function( x, t, b, c, d ) {
      if ( t < d / 2 ) return 2 * c * t * t / ( d * d ) + b;
      var a = t - d / 2;
      return -2 * c * a * a / ( d * d ) + 2 * c * a / d + c / 2 + b
    },
    easeout: function( x, t, b, c, d ) {
      return -c * t * t / ( d * d ) + 2 * c * t / d + b
    },
    backout: function( x, t, b, c, d ) {
      var s = 1.70158;
      return c * ( ( t = t / d - 1 ) * t * ( ( s + 1 ) * t + s ) + 1 ) + b
    },
    linear: function( x, t, b, c, d ) {
      return c * t / d + b
    }
  } );

  $.fn.extend( {
    lavalamp: function( o ) {
      o = $.extend( {
        fx: "linear",
        speed: 500,
        click: function() {}
      }, o || {} );
      return this.each( function() {
        var b = $( this ),
          $back = $( '<li class="back"><div class="left"></div></li>' ).appendTo( b ),
          $li = $( "li", this ),
          curr = $( "li.current", this )[ 0 ] || $( $li[ 0 ] ).addClass( "current" )[ 0 ];
        $li.click( function( e ) {
          if ( $( this ).hasClass( 'back' ) ) {
            return;
          }
          move( this );
          $( this ).addClass( 'current' ).siblings().removeClass( 'current' );
          return o.click.apply( this, [ e, this ] )
        } );
        setCurr( curr );

        function setCurr( a ) {
          $back.css( {
            "left": a.offsetLeft + "px",
            "width": a.offsetWidth + "px"
          } );
          curr = a
        };

        function move( a ) {
          $back.each( function() {
            $.dequeue( this, "fx" )
          } ).animate( {
            width: a.offsetWidth,
            left: a.offsetLeft
          }, o.speed, o.fx )
        }
      } );
    },
    /* 分页使用方法类同于Pagination */
    bwPagination: function( option ) {
      var DEFAULTOPTION = {
          align: 'right',
          total: 0,
          currentPage: 1,
          pageCount: 10,
          text: '跳转',
          autoVisibility: 0
        },
        html = '';
      $.extend( DEFAULTOPTION, option );
      html += '<div class="pageControl_inner">'
      html += '<button type="button" class="btn btn-default glyphicon glyphicon-menu-left gray prev" disabled="disabled"></button>';
      html += '<span class="gray pagenum">&nbsp;<span class="current_page">1</span>&nbsp;/&nbsp;<span class="maxPage">1</span>&nbsp;</span>';
      html += '<button type="button" class="btn btn-default glyphicon glyphicon-menu-right gray next" disabled="disabled"></button>&nbsp;';
      html += '<input type="text" class="inp_page">&nbsp;';
      html += '<button type="button" class="btn btn-default goPage"></button>';
      html += '</div>';
      html = $( html );

      function disabledCheck( opt, max ) {
        if ( opt.currentPage < 2 ) {
          $( '.prev', this ).prop( 'disabled', 'disabled' );
        } else {
          $( '.prev', this ).removeAttr( 'disabled' );
        }
        if ( opt.currentPage >= max ) {
          $( '.next', this ).prop( 'disabled', 'disabled' );
        } else {
          $( '.next', this ).removeAttr( 'disabled' );
        }
        if ( $.isFunction( opt.callback ) ) {
          opt.callback.call( this, opt.currentPage );
        }
      }
      return $( this ).each( function() {
        var self = $( this ),
          opt = DEFAULTOPTION,
          maxPage = parseInt( opt.total / opt.pageCount );
        if ( opt.total % opt.pageCount > 0 ) {
          ++maxPage;
        }
        if ( maxPage > 1 && opt.currentPage != maxPage ) {
          $( 'button.next', html ).removeAttr( 'disabled' );
        }
        if ( !self.hasClass( 'pageControl' ) ) {
          self.addClass( 'pageControl' );
        }
        if ( opt.currentPage > 1 ) {
          $( 'button.prev', html ).removeAttr( 'disabled' );
        }
        $( '.maxPage', html ).text( maxPage ).data( 'maxPage', maxPage );
        $( '.current_page', html ).text( opt.currentPage ).data( 'currentPage', opt.currentPage );;
        $( '.goPage', html ).text( opt.text );

        self.css( {
          'text-align': opt.align
        } ).html( html ).on( 'pageChange', function( e, page ) { // 自定义事件，监听page变化
          alert( page );
          $( '.current_page', this ).text( opt.currentPage = page );
          disabledCheck.call( self, opt, maxPage );
        } ).on( 'nextPage', function() {
          $( 'button.next', this ).trigger( 'click' );
        } ).on( 'prevPage', function() {
          $( 'button.prev', this ).trigger( 'click' );
        } );

        html.on( 'click', '.next', function() {
          if ( opt.currentPage < maxPage ) {
            $( '.current_page', html ).text( ++opt.currentPage );
          }
          disabledCheck.call( self, opt, maxPage );
        } ).on( 'click', '.prev', function() {
          if ( opt.currentPage > 1 ) {
            $( '.current_page', html ).text( --opt.currentPage );
          }
          disabledCheck.call( self, opt, maxPage );
        } ).on( 'click', '.goPage', function() {
          opt.currentPage = $( '.inp_page', self ).val() || 1;
          $( '.current_page', html ).text( opt.currentPage );
          disabledCheck.call( self, opt, maxPage );
        } ).on( 'change keyup', '.inp_page', function() {
          var page = parseInt( $( this ).val() );
          if ( page >= maxPage ) {
            $( this ).val( maxPage );
          } else {
            if ( !page ) {
              $( this ).val( '' );
            } else {
              $( this ).val( page );
            }
          }
        } );
        if ( opt.autoVisibility ) {
          if ( maxPage > 1 ) {
            $( this ).css( 'visibility', 'visible' );
          } else {
            $( this ).css( 'visibility', 'hidden' );
          }
        }

      } );
    },
    /**
     * 滚动条滚动到最底部要触发的事件
     * @param 执行的事
     * @param （修正）滚动的底部距离这个滚动条底部的距离，默认10px 
     */
    scrollMax: function( fn, percent ) {
      //$callback  =  typeof fn  ===  "function"  ?  fn  :  undefined;
      percent = percent || 10;
      var $thisObj = $( this );
      $thisObj.scroll( function() {
        var scrollHeight = $thisObj[ 0 ].scrollHeight;
        var thisHeight = $thisObj.outerHeight();
        var scrollTop = $thisObj.scrollTop();
        /*if ((scrollTop + thisHeight) / scrollHeight >= percent) {
        	if (fn){
        		fn.call($this[0], thisHeight)
        	}
        }*/
        if ( scrollHeight - ( scrollTop + thisHeight ) <= percent ) {
          if ( fn ) {
            fn.call( $thisObj[ 0 ], thisHeight )
          }
        }
      } );
      return $( this );
    },
    /**
     * 栏目类， 参数一位数组['栏目1', '栏目2', '栏目3']
     * 参数二 点击后的回调 回调当前点击对象 可获取index 和点击前的对象 用于tab切换
     * @param columns 可配置为数组或对象  对象可配置其默认显示或隐藏状态
     */
    bwColumns: function( columns, fn, index, target ) {
      return $( this ).each( function() {
        var $this = $( this ),
          showCfg;
        if ( !$this.hasClass( 'bw-columns' ) ) {
          $this.addClass( 'bw-columns' );
        }
        if ( typeof index != 'number' ) {
          target = index;
          index = undefined;
        }
        if ( !( columns instanceof Array ) ) {
          showCfg = columns.showCfg;
          columns = columns.columns
        }

        function isShowCfg( columIndex ) {
          if ( showCfg && !showCfg[ columIndex ] ) {
            return ' style="display: none;"';
          } else {
            return '';
          }
        }
        var html = '<ul>';
        if ( columns ) {
          for ( i in columns ) {
            if ( typeof index != 'undefined' ) {
              if ( i == index ) {
                html += '<li class="selected" ' + isShowCfg( i ) + '>' + columns[ i ] + '</li>';
              } else {
                html += '<li ' + isShowCfg( i ) + '>' + columns[ i ] + '</li>';
              }
            } else {
              if ( i == 0 ) {
                html += '<li class="selected" ' + isShowCfg( i ) + '>' + columns[ i ] + '</li>';
              } else {
                html += '<li ' + isShowCfg( i ) + '>' + columns[ i ] + '</li>';
              }
            }
          }
        }
        html += '<div class="hover-line"></div></ul>';
        $this.append( html );
        $this.find( '.hover-line' ).width( $this.find( '.selected' ).outerWidth() );
        $this.find( '.hover-line' ).transit( {
          x: $this.find( '.selected' ).position().left
        } );
        /*$this.find('li:not(.hover-line)').hover(function() {
        	$this.find('.hover-line').width($(this).outerWidth());
        	$this.find('.hover-line').css('left', $(this).position().left);
        }, function() {
        	$this.find('.hover-line').width($this.find('.selected').outerWidth());
        	$this.find('.hover-line').css('left', $this.find('.selected').position().left);
        });*/

        $this.find( 'li:not(.hover-line)' ).click( function() {
          if ( $( this ).hasClass( 'selected' ) ) return;
          var prevObj = $this.find( '.selected' );
          $( this ).addClass( "selected" ).siblings().removeClass( "selected" );
          $this.find( '.hover-line' ).width( $( this ).outerWidth() );
          $this.find( '.hover-line' ).transit( {
            x: $( this ).position().left
          } );
          var clickThis = $( this );
          if ( target ) {
            $( '>*', target ).eq( clickThis.index() ).fadeIn().siblings().hide();
          }
          if ( fn ) {
            fn.call( $this, clickThis, prevObj );
          }
        } );
        $this.find( '.selected' ).bind( 'DOMNodeInserted', function( e ) {
          $( this ).trigger( 'mouseenter' );
        } );
      } );
    },
    /**
     * 让一个标签在body滚动时超出窗口位置置顶
     * @param option.datumTop 距离顶部位置
     * @param （修正）滚动的底部距离这个滚动条底部的距离，默认10px 
     * @param style  额外的样式附加
     * @param autoFullPlace 是否开启自动填充原先的位置 默认true
     * @param reservedStyle  需要保留的样式
     */
    keepOn: function( option ) {
      var defualtOptions = {
        align: 'top',
        datumTop: 0,
        style: {},
        autoFullPlace: true,
        reservedStyle: {}
      };
      if ( option && typeof option !== 'object' ) {
        defualtOptions.datumTop = option;
      } else {
        $.extend( defualtOptions, option );
      }
      return $( this ).each( function() {
        var $thisObj = $( this ),
          $thisTop = $thisObj.offset().top,
          thisLeft = $thisObj.offset().left;

        function scroll() {
          var thisTopWindow = $thisObj.offset().top - $( this ).scrollTop();
          if ( thisTopWindow < defualtOptions.datumTop ) {
            if ( $thisObj.css( 'position' ) !== 'fixed' ) {
              defualtOptions.autoFullPlace && $thisObj.before( $( '<div></div>' ).css( {
                width: $thisObj.outerWidth( true ),
                height: $thisObj.outerHeight( true ),
                display: 'inline-block'
              } ) );

              $thisObj.css( $.extend( {
                'position': 'fixed',
                'top': defualtOptions.datumTop,
                'left': $thisObj.offset().left,
                '-bwekit-transition': 'all .5s ease',
                'width': $thisObj.outerWidth(),
                'margin-left': 0,
                'z-index': 2
              }, defualtOptions.style ) ).addClass( 'active-affix' )

            }
          }
          if ( ( $thisTop - $( this ).scrollTop() ) >= defualtOptions.datumTop ) {
            if ( $thisObj.css( 'position' ) == 'fixed' ) {
              $thisObj.removeAttr( 'style' );
              $thisObj.css( defualtOptions.reservedStyle ).removeClass( 'active-affix' );
              defualtOptions.autoFullPlace && $thisObj.prev().remove();
            }
          }
        }
        scroll.call( $( document ).scroll( scroll ) );
      } );
    },
    /**
     * format文章预览内容的东西视频/图片宽高等~
     */
    mediaFormat: function() {

      function RegExpUrlFactory( name ) {
        return new RegExp( '' + name + '=([^&]*)', 'g' );
      }

      function RegExpStyleFactory( name ) {
        return new RegExp( '' + name + ':([^;]*)', 'g' );
      }

      return $( this ).each( function() {
        var self = this;

        $( '.video_iframe', this ).each( function() {
          $( this ).prop( 'scrolling', 'no' );

          var iframe_src = $( this ).prop( 'src' ) || '',
            thisWidth = $( self ).width(),
            thisHeight = thisWidth * .75,
            replaceUrl = iframe_src.replace( /preview\.html/, "player.html" )
            .replace( RegExpUrlFactory( 'width' ), 'width=' + thisWidth )
            .replace( RegExpUrlFactory( 'height' ), 'height=' + thisHeight );
          if ( replaceUrl ) {
            var thisStyle = $( this ).attr( 'style' ) || '',
              widthStyle = 'width: ' + thisWidth + 'px !important',
              heightStyle = 'height: ' + thisHeight + 'px !important';
            if ( thisStyle.match( RegExpStyleFactory( 'width' ) ) ) {
              thisStyle = thisStyle.replace( RegExpStyleFactory( 'width' ), widthStyle );
            } else {
              thisStyle += widthStyle + ';';
            }

            if ( thisStyle.match( RegExpStyleFactory( 'height' ) ) ) {
              thisStyle = thisStyle.replace( RegExpStyleFactory( 'height' ), heightStyle );
            } else {
              thisStyle += heightStyle + ';';
            }
            $( this ).prop( 'src', replaceUrl )
              .css( 'cssText', thisStyle );
          }
        } );

        $( 'img', this ).css( {
          'height': 'auto !important'
        } );
      } );

    },
    mediaSrcAttr: function() {
      $( 'img', this ).each( function() {
        // prop attr  prop会取的带有域名的前缀  attr原样返回
        var $src = $( this ).attr( 'src' );
        if ( $src ) {
          $( this ).prop( 'src', returnParam.wechartImgCheck( $src ) );
        } else {
          var $datasrc = $( this ).attr( 'data-src' );
          if ( $datasrc ) {
            $( this ).prop( 'src', returnParam.wechartImgCheck( $datasrc ) );
          }
        }
      } );
      $( 'iframe', this ).each( function() {
        var $datasrc = $( this ).attr( 'data-src' );
        if ( $datasrc ) {
          $( this ).prop( 'src', $datasrc );
        }
      } );

      $( 'section,div,blockquote,span', this ).each( function() {
        var bgImg = $( this ).css( 'background-image' );
        if ( bgImg && bgImg != 'none' && bgImg.toLowerCase().indexOf( 'url(' ) > -1 ) {
          bgImg = bgImg.substr( 0, bgImg.lastIndexOf( '")' ) ).replace( 'url("', '' );
          $( this ).css( {
            'background-image': 'url(' + returnParam.wechartImgCheck( bgImg, !0 ) + ')'
          } )
        }
      } );

      return this;
    },
    /**
     * [阻止滚动区域的向上冒泡]【相当于重写了scroll事件】
     * @return {[type]} [description]
     */
    preventScroll: function() {

      return $( this ).each( function() {
        var _this = this;
        if ( navigator.userAgent.toLowerCase().indexOf( "firefox" ) > 0 ) {
          _this.addEventListener( 'DOMMouseScroll', function( e ) {
            //_this.scrollTop += e.detail > 0 ? 60 : -60;
            if ( this.scrollTop + this.clientHeight == this.scrollHeight && e.detail > 0 ) {
              e.preventDefault();
              e.returnValue = false;
            } else if ( this.scrollTop === 0 && e.detail < 0 ) {
              e.preventDefault();
              e.returnValue = false;
            }
          }, false );
        } else {
          _this.addEventListener( 'mousewheel', function( e ) {
            /*e = e || window.event;
            _this.scrollTop += e.wheelDelta > 0 ? -60 : 60;
            e.preventDefault();
            e.returnValue = false;*/
            if ( this.scrollTop + this.clientHeight == this.scrollHeight && e.wheelDelta < 0 ) {
              e.preventDefault();
              e.returnValue = false;
            } else if ( this.scrollTop === 0 && e.wheelDelta > 0 ) {
              e.preventDefault();
              e.returnValue = false;
            }
          }, false );
        }
        return this;
      } );

    }
  } );

  /**
   * 时间对象的格式化;
   */
  Date.prototype.format = function( format ) {
    /*
     * eg:format="yyyy-MM-dd hh:mm:ss";
     */
    var o = {
      "M+": this.getMonth() + 1, // month
      "d+": this.getDate(), // day
      "h+": this.getHours(), // hour
      "m+": this.getMinutes(), // minute
      "s+": this.getSeconds(), // second
      "q+": Math.floor( ( this.getMonth() + 3 ) / 3 ), // quarter
      "S": this.getMilliseconds()
      // millisecond
    }
    if ( /(y+)/.test( format ) ) {
      format = format.replace( RegExp.$1, ( this.getFullYear() + "" ).substr( 4 - RegExp.$1.length ) );
    }
    for ( var k in o ) {
      if ( new RegExp( "(" + k + ")" ).test( format ) ) {
        format = format.replace( RegExp.$1, RegExp.$1.length == 1 ? o[ k ] : ( "00" + o[ k ] ).substr( ( "" + o[ k ] ).length ) );
      }
    }
    return format;
  };

  /**
   * str 要截取的字符穿
   * len要截取的长度，根据字节计算
   * suffix截取前len个后，其余的字符的替换字符一般用“…”
   */
  String.prototype.cutStringByte = function( len, suffix ) {
    str = this;
    if ( !str ) return "";
    if ( len <= 0 ) return "";
    if ( !suffix ) suffix = "";
    var templen = 0;
    for ( var i = 0; i < str.length; i++ ) {
      if ( str.charCodeAt( i ) > 255 ) {
        templen += 2;
      } else {
        templen++
      }
      if ( templen == len ) {
        return str.substring( 0, i + 1 ) + suffix;
      } else if ( templen > len ) {
        return str.substring( 0, i ) + suffix;
      }
    }
    return str + '';
  }

  if ( "ActiveXObject" in window ) {
    window.URL = function( url ) {
      if ( !returnParam.isUrlCheck( url ) ) {
        throw new Error( '不是正确的url地址' );
        return;
      }
      $.extend( this, returnParam.parseURL( url ) );
    }
  }

  return returnParam
} );
